import { Button, Swiper, SwiperItem, View,Image,Text } from '@tarojs/components'
import React, { useEffect, useState } from 'react'
import Taro, { useDidShow, useReachBottom, useShareAppMessage } from '@tarojs/taro'
import { checkSalesMan } from '@/utils/Tools';
import { AtModal } from 'taro-ui'
import {handleCityName} from '@/utils/Tools'
import './index.scss'
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/modal.scss";

export default function Index() {
  let capsuleInfo = {}
  if(process.env.TARO_ENV === 'weapp') capsuleInfo = Taro.getMenuButtonBoundingClientRect()
  const [user, setUser] = useState(Taro.getStorageSync('user'))
  let moreMap = {
    'more':'加载更多',
    'loading':'加载中~',
    'no-more':'已经到底啦~',
  }
  const [categoryList,setCategoryList] = useState([])
  const [showDrop, setshowDrop] = useState(null)
  const [curTabs, setcurTabs] = useState(0)
  const [tabsList,setTabsList] = useState([])
  const [hotList,setHotList] = useState([])
  const [swiperList,setSwiperList] = useState([])
  const [params,setParams] = useState({
    page:1,
    pageSize:10,
    type:0
  })
  const [moreStatus,setmoreStatus] = useState(null)
  const [location,setLocation] = useState({})
  const [otherList,setOtherList] = useState([])

  useEffect(()=>{
    const {router} = Taro.getCurrentInstance()
    if(process.env.TARO_ENV == 'h5'){
      handleCityName()
    }else{
      init()
    }
    checkSalesMan(router.params)
  },[])
  useDidShow(()=>{
    setUser(Taro.getStorageSync('user'))
    Taro.eventCenter.off('updateLogin')
    Taro.eventCenter.on('updateLogin',(res)=>{
      setUser(Taro.getStorageSync('user'))
    })
    Taro.eventCenter.off('updateLocation')
    Taro.eventCenter.on('updateLocation',(res)=>{
      updateLocation()
      init()
    })
    updateLocation()
  })
  useShareAppMessage(()=>{
    return {
      title: '小聚团',
      path: '/pages/index/index'
    }
  })
  useReachBottom(()=>{
    if(params.total > hotList.length){
      _getHotList({page:params.page+1},e=>{
        setHotList([...hotList,...e.records])
      })
    }else{
      setmoreStatus("no-more")
    }
  })
  function init(){
    Taro.$get('/act/index/selectAdvertisingListByAlias/_xjtsy').then(res=>{
      setSwiperList(res.content.advertisesList || [])
    })
    _initData()
  }
  function updateLocation(){
    const loca = Taro.getStorageSync('cityInfo')
    if(loca && loca.cityCode){
      setLocation(loca || {})
    }
  }
  function handleToBanner(e){
    if(process.env.TARO_ENV == 'h5'){
      if(e.url.includes('http')){
        location.href = e.url
      }else{
        Taro.navigateTo({
          url:e.url
        })
      }
      return;
    }
    if(e.url.includes('http')){
      Taro.navigateTo({
        url:`/pages/fineEngine/webView?url=${e.url}`
      })
      return;
    }
    Taro.navigateTo({
      url:e.url
    })
  }
  const handleTabs = e=>{
    setcurTabs(e)
    _getHotList({page:1,...tabsList[e]})
  }
  function handleToDetail(e){  ///   跳详情
    Taro.navigateTo({
      url:`/mainPages/event-detail/index?id=${e.id}`
    })
  }
  
  ///      network
  const _initData = async ()=>{
    // Taro.$get('/act/gathers',).then(res=>{
    //   setCategoryList(res.content || [])
    // })
    Taro.$get('/act/gathers/embedded/scheduleDate',{
      cityCode:Taro.getStorageSync('cityInfo').cityCode || 0,
      flag:'0'
    }).then(res=>{
      if(res.content.length){
        setTabsList([{
          dateDesc: "ALL",
          dateStr: "全部"
        },...res.content])
        _getHotList({page:1,
          dateDesc: "ALL",
          dateStr: "全部"
        })
      }
    })
  }
  const _getHotList = async (e,func)=>{  //  获取活动列表
    const loca = Taro.getStorageSync('cityInfo')
    setmoreStatus('more')
    Taro.showLoading({
      title:'加载中...'
    })
    const data = {
      ...params,
      cityCode:loca.cityCode||0,
      page:params.page,
      pageSize:params.pageSize,
      ...e
    }
    if(data.scheduleDate == '0'){
      data.scheduleDate = undefined
      data.dateDesc = undefined
      data.dateStr = undefined
    }
    if(loca && loca.latitude){
      Object.assign(data,{
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    if(data.dateDesc == 'ALL') delete data.scheduleDate
    const res = await Taro.$post('/act/gathers/embedded/list',data,'1')
    if(res.code == '1'){
      setshowDrop(null)
      // if(res.content.total < 10){
      //   _getOtherEvent(e)
      // }
      setParams({...data,total:res.content.total})
      setmoreStatus('no-more')
      if(func){
        func(res.content)
        return;
      }
      setHotList(res.content.records)
    }
  }
  function _getOtherEvent(values){  ///  获取其他城市列表
    const loca = Taro.getStorageSync('cityInfo')
    let data = {
      dateStr:values.dateStr,
      scheduleDate:values.scheduleDate
    }
    if(data.scheduleDate == '0'){
      data.scheduleDate = undefined
      data.dateStr = undefined
    }
    if(loca && loca.latitude){
      Object.assign(data,{
        cityCode:loca.cityCode,
        latitude:loca.latitude,
        longitude:loca.longitude
      })
    }
    Taro.$post('/act/gather/otherCityV2',data).then(result=>{
      if(result.code === '1'){
        setOtherList(result.content)
      }
    })
  }
  
  return (
    <View className={`home`} style={showDrop?{height:'100vh',overflow:'hidden'}:null}>
      <View class="home-crumbs" style={{'paddingTop': `${(capsuleInfo.top||0)+(capsuleInfo.height||0)+10}px`}}>
        {user.token?
        <View class="crumbs-main">
          <Image src={user.avatar} class="main-logo"></Image>
          <View className='h2' style={{whiteSpace:'nowrap'}}>{user.userNo}</View>
        </View>:
        <View class="crumbs-main" onClick={()=>{
          Taro.navigateTo({
            url:'/pages/other/login/index'
          })
        }}>
          <Image src={require('@/static/Avatar.svg')} class="main-logo"></Image>
          <View className='h2' style={{whiteSpace:'nowrap'}}>登录</View>
        </View>}
        <View className='crumbs-person' onClick={()=>{
          Taro.navigateTo({
            url:'/pages/mine/index/index'
          })
        }}>个人中心 <View className='at-icon at-icon-chevron-right' style={{fontSize:14}}></View></View>
      </View>
      <View className="home-main">
        {swiperList.length?<>
          {swiperList.length > 1?
          <View className="home-swiper">
            <Swiper className="swiper-main" autoplay={true} interval={3000} duration={1000}>
              {swiperList.map(item=>{
                return <SwiperItem key={item.id} onClick={()=>{handleToBanner(item)}}>
                <Image className="img" src={item.imageUrl} mode="aspectFill"></Image>
              </SwiperItem>
              })}
            </Swiper>
          </View>:
          <View className='home-swiper'><Image className="img" src={swiperList[0].imageUrl} mode="aspectFill"></Image></View>}
        </>:null}

        {false?
        <View className="home-category">
          <View className="category-list not-bar">
            {categoryList.map((item,idx)=>{
              return <View className="list-item" key={idx} onClick={e=>{
                if(item.appId){
                  Taro.navigateToMiniProgram({
                    appId: item.appId,
                    path: item.urlPath,
                  })
                  return;
                }
                Taro.navigateTo({
                  url:`/mainPages/zone/index?id=${item.typeId}`
                })
              }}>
                <Image src={item.imageUrl} className='item-img' />
                {item.title}
              </View>
            })}
          </View>
        </View>:null}

        {tabsList.length?<>
        <View className="home-tabs">
          <View className="tabs-list not-bar">
            {tabsList?.map((item,idx)=>{
              return <View className={`tabs-item ${curTabs == idx?'active':''}` } key={item.id} onClick={()=>{handleTabs(idx)}}>
              <View className='item-h2'>{item.dateStr}</View> <Text>{item.dateDesc}</Text>
            </View>
            })}
          </View>
        </View>
        <View className="home-screen">
          {showDrop == 'activity'?
          <View className="item-drop" onClick={()=>{setshowDrop(null)}}>
            <View className="drop-activity">
              {categoryList.map((item,idx)=>{
                return <View className="drop-list" key={idx} onClick={e=>{
                  if(item.appId){
                    Taro.navigateToMiniProgram({
                      appId: item.appId,
                      path: item.urlPath,
                    })
                    return;
                  }
                  Taro.navigateTo({
                    url:`/mainPages/zone/index?id=${item.typeId}`
                  })
                }}>{item.title}</View>
              })}
            </View>
          </View>:null}
          {showDrop == 'type'?
          <View className="item-drop" onClick={()=>{setshowDrop(null)}}>
            <View className="drop-sort">
              <View className={`drop-list ${params.type == 0?'active':''}`} onClick={(e)=>{
                _getHotList({page:1,type:0})
              }}>离我最近</View>
              <View className={`drop-list ${params.type == 1?'active':''}`} onClick={(e)=>{
                _getHotList({page:1,type:1})
              }}>价格最低</View>
            </View>
          </View>:null}
          <View className='screen-item' onClick={()=>{
            Taro.navigateTo({
              url:'/mainPages/city-list/index'
            })
          }}>{location.name?.replace("市", "") || '全国'} <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View></View>
          {/* <View className={`screen-item ${showDrop == 'activity'?'theme-color':''}`} onClick={()=>{
            if(!categoryList.length) return;
            setshowDrop(null)
            if(showDrop!='activity'){
              setshowDrop('activity')
            }
          }}>全部活动 <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View></View> */}
          <View className={`screen-item ${showDrop == 'type'?'theme-color':''}`} onClick={()=>{
            setshowDrop(null)
            if(showDrop!='type'){
              setshowDrop('type')
            }
          }}>{params.type == '1'?'价格最低':'离我最近'} <View className="at-icon at-icon-chevron-down" style={{fontSize:14}}></View></View>
        </View>
        </>:<View className='var-empty'>
          <View className="h2">「{location.name?.replace("市", "") || '全国'}」最近没有场次安排</View>
          <View className="p">后续会发布新的活动场次，敬请期待哦~</View>
        </View>}
        
        {hotList.length?<View className="home-hot">
          {hotList.map(item=>{
            return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
              <View className="hot-item">
                <View className="item-img">
                  {item.sellOut?<View className="item-mask"><Image className="mask-img" src={require('../../static/soldout.png')}></Image></View>:null}
                  <Image className="img-pic" src={Taro.getMedia(item.logoUrl)} mode="aspectFill"></Image>
                </View>
                <View className="item-info">
                  <View className="dot h2">{item.locationName}</View>
                  {item.tagsJson?
                  <View className="info-list">
                    {item.tagsJson.map(tag=>{
                      return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                    })}
                  </View>:null}
                  <View className="h4 dot"><Image src={require('@/static/icon_calendar.png')} /> {item.dateStr}</View>
                  {item.hallName?<View className="h4 dot"><Image src={require('@/static/icon-space.png')} /> {item.hallName}</View>:null}
                  <View className="h4"><Image src={require('@/static/icon_map-pin.png')} />{item.distance?<Text style={{marginRight:4}}>{item.distance}</Text>:''}<Text className='dot'>{item.locationAddress}</Text></View>
                  {item.establishTickets > 0?
                  <View className="list-item">
                    {item.isEstablish?<>
                    <Image className='image' src={require('@/static/checked-true.svg')}></Image>
                    <Text className='strong'>已成团</Text>
                    <Text className='span'>已报名{item.recordNum}人{item.maxTickets?`（满场${item.maxTickets}人）`:null}</Text>
                    </>:<>
                    <Text className='strong'>{item.establishTickets}人开场{item.recordNum>0?'，已组'+item.recordNum+'人':''}</Text>
                    <Text className='span'>{item.remainTimeDesc}</Text>
                    </>}
                  </View>:null}
                </View>
              </View>
              <View className="item-footer">
                <View className="footer-merchant">
                  <Image className='logo' src={item.merchantUrl} />
                  <View>{item.merchantName}</View>
                  <Image className='icon' src={require('@/static/verified.png')} />
                </View>
                <View className="footer-price">¥ <Text style={{fontSize:18,margin:"0 1px"}}>{item.price}</Text> {item.areaPrice=='2'?'起':''}</View>
              </View>
            </View>
          })}
        </View>:tabsList.length?<View className='var-empty'>
          <View className="h2">「{location.name?.replace("市", "") || '全国'}」最近没有场次安排</View>
          <View className="p">后续会发布新的活动场次，敬请期待哦~</View>
        </View>:null}
        {otherList?.length && location.cityCode != '0'?<>
          <View className="other-title h2">其他城市活动</View>
          <View className="home-hot">
            {otherList.map(item=>{
              return <View className="hot-list" key={item.id} onClick={()=>{handleToDetail(item)}}>
              <View className="hot-item">
                <View className="item-img">
                  {item.sellOut?<View className="item-mask"><Image className="mask-img" src={require('../../static/soldout.png')}></Image></View>:null}
                  <Image className="img-pic" src={Taro.getMedia(item.logoUrl)} mode="aspectFill"></Image>
                </View>
                <View className="item-info">
                  <View className="dot h2">{item.locationName}</View>
                  {item.tagsJson?
                  <View className="info-list">
                    {item.tagsJson.map(tag=>{
                      return <Text className={`${tag.source == 'PLATFORM'?'red':''}`} key={tag.tagName}>{tag.tagName}</Text>
                    })}
                  </View>:null}
                  <View className="h4 dot"><Image src={require('@/static/icon_calendar.png')} /> {item.dateStr}</View>
                  {item.hallName?<View className="h4 dot"><Image src={require('@/static/icon-space.png')} /> {item.hallName}</View>:null}
                  <View className="h4"><Image src={require('@/static/icon_map-pin.png')} />{item.distance?<Text style={{marginRight:4}}>{item.distance}</Text>:''}<Text className='dot'>{item.locationAddress}</Text></View>
                  {item.establishTickets>0?
                  <View className="list-item">
                    {item.isEstablish?<>
                    <Image className='image' src={require('@/static/checked-true.svg')}></Image>
                    <Text className='strong'>已成团</Text>
                    <Text className='span'>已报名{item.recordNum}人{item.maxTickets?`（满场${item.maxTickets}人）`:null}</Text>
                    </>:<>
                    <Text className='strong'>{item.establishTickets}人开场{item.recordNum>0?'，已组'+item.recordNum+'人':''}</Text>
                    <Text className='span'>{item.remainTimeDesc}</Text>
                    </>}
                  </View>:null}
                </View>
              </View>
              <View className="item-footer">
                <View className="footer-merchant">
                  <Image className='logo' src={item.merchantUrl} />
                  <View>{item.merchantName}</View>
                  <Image className='icon' src={require('@/static/verified.png')} />
                </View>
                <View className="footer-price">¥ <Text style={{fontSize:18,margin:"0 1px"}}>{item.price}</Text> {item.areaPrice=='2'?'起':''}</View>
              </View>
            </View>
            })}
          </View>
        </>:null}
      {hotList.length && moreStatus?<View className="var-more">{moreMap[moreStatus]}</View>:null}
      </View>
    </View>
  )
}
